<?php

class Article_Model extends Model {

    public function __construct() {
        parent::__construct();

    }

    public function getData() {
        //echo "1";
        $data = array('msg'=>'', 'list'=>null);

        //insert article
        if (isset($_POST['action']) && $_POST['action'] == 'add' && (!empty($_POST['name_cn']) || !empty($_POST['name_de']) )) {
            //echo "2";
            $ean = trim($_POST['ean']);
            $name_cn = trim($_POST['name_cn']);
            $name_de = trim($_POST['name_de']);


            $sth = $this->db->prepare("SELECT * FROM article WHERE ean = :ean");
            //echo "3";
            $sth->execute(array(':ean' => $ean));
            $sth->fetch();
            if ($sth->rowCount() > 0){
                //echo "4";
                 $data['msg'] = '<div class="errorMsg">Ein Artikel mit dieser EAN-Nr '. filter_var($ean, FILTER_SANITIZE_STRING) .' schon angelegt.</div>';
            }else{
               try{
                   //echo "5";
                 $this->db->insert('article', array('ean'=>$ean, 'name_cn'=>$name_cn, 'name_de'=>$name_de));
                 $data['msg'] = '<div class="successMsg">'.filter_var($ean, FILTER_SANITIZE_STRING) .' | '.filter_var($name_de, FILTER_SANITIZE_STRING) .' | '.filter_var($name_cn, FILTER_SANITIZE_STRING) .' wurde angelegt.</div>';
               }catch (Exception $e) {
                    echo 'Exception: article cannot be inserted: ',  $e->getMessage(), "\n";
               }
            }
        }
        //echo "6";

        //remove article
        if (isset($_POST['action']) && $_POST['action'] == 'del' && isset($_POST['articleId']) &&(is_array($_POST['articleId']) && count($_POST['articleId']) > 0 )) {
            $where = "id IN (".implode(' ,', $_POST['articleId']).")";
            //echo $where;
            $this->db->delete('article', $where);
        }
        //var_dump($_POST);

        $data['list'] = $this->db->select("SELECT * FROM article ");

        //var_dump($data);
        return $data;
    }

}